<template>
  <view class="order-detail-container">
    <!-- 页面标题 -->
    <view class="header">
      <text class="header-title">订单详情</text>
    </view>

    <view v-if="orderDetail" class="detail-content">
      <!-- 基本信息 -->
      <view class="detail-section">
        <view class="section-title">基本信息</view>
        <view class="detail-row">
          <text class="detail-label">订单号：</text>
          <text class="detail-value">{{ orderDetail.order_number }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">车牌号：</text>
          <text class="detail-value">{{ orderDetail.license_plate }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">用户：</text>
          <text class="detail-value">{{ orderDetail.user_nickname || '未知用户' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">手机号：</text>
          <text class="detail-value">{{ orderDetail.user_phone || '未提供' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">状态：</text>
          <text class="detail-value" :class="getStatusClass(orderDetail.status)">
            {{ getStatusText(orderDetail.status) }}
          </text>
        </view>
        <view class="detail-row">
          <text class="detail-label">停车类型：</text>
          <text class="detail-value parking-type" :class="orderDetail.parking_type">
            {{ orderDetail.parking_type === "outdoor" ? "🌤️ 室外停车" : "🏠 室内停车" }}
          </text>
        </view>
      </view>

      <!-- 时间信息 -->
      <view class="detail-section">
        <view class="section-title">时间信息</view>
        <view class="detail-row">
          <text class="detail-label">预计入场：</text>
          <text class="detail-value">{{ formatDateTime(orderDetail.planned_start_time) }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">预计离场：</text>
          <text class="detail-value">{{ formatDateTime(orderDetail.planned_end_time) }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">实际入场：</text>
          <text class="detail-value">{{ orderDetail.actual_start_time ? formatDateTime(orderDetail.actual_start_time) : '未入场' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">实际离场：</text>
          <text class="detail-value">{{ orderDetail.actual_end_time ? formatDateTime(orderDetail.actual_end_time) : '未离场' }}</text>
        </view>
      </view>

      <!-- 费用信息 -->
      <view class="detail-section">
        <view class="section-title">费用信息</view>
        <view class="detail-row">
          <text class="detail-label">总金额：</text>
          <text class="detail-value">¥{{ orderDetail.total_amount }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">优惠金额：</text>
          <text class="detail-value">¥{{ orderDetail.discount_amount }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">实付金额：</text>
          <text class="detail-value amount">¥{{ orderDetail.final_amount }}</text>
        </view>
      </view>

      <!-- 编辑时间区域 -->
      <view class="edit-time-section">
        <view class="section-title">编辑实际时间</view>
        
        <view class="time-edit-row">
          <text class="time-edit-label">实际入场时间：</text>
          <view class="datetime-picker">
            <picker mode="date" :value="editForm.start_date" @change="onStartDateChange">
              <view class="datetime-value">
                {{ editForm.start_date || '选择日期' }}
              </view>
            </picker>
            <picker mode="time" :value="editForm.start_time" @change="onStartTimeChange">
              <view class="datetime-value">
                {{ editForm.start_time || '选择时间' }}
              </view>
            </picker>
          </view>
        </view>
        
        <view class="time-edit-row">
          <text class="time-edit-label">实际离场时间：</text>
          <view class="datetime-picker">
            <picker mode="date" :value="editForm.end_date" @change="onEndDateChange">
              <view class="datetime-value">
                {{ editForm.end_date || '选择日期' }}
              </view>
            </picker>
            <picker mode="time" :value="editForm.end_time" @change="onEndTimeChange">
              <view class="datetime-value">
                {{ editForm.end_time || '选择时间' }}
              </view>
            </picker>
          </view>
        </view>
        
        <view class="time-edit-row">
          <text class="time-edit-label">备注：</text>
          <textarea 
            class="time-edit-textarea" 
            v-model="editForm.notes"
            placeholder="请输入操作备注"
            maxlength="200"
          />
        </view>
        
        <view class="save-actions">
          <button class="save-btn" @click="saveOrderTime">保存时间</button>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { request } from '../../utils/request.js'
import { parkingOperatorGuard } from '../../utils/roleGuard.js'

// 响应式数据
const loading = ref(false)
const orderId = ref(null)
const orderDetail = ref(null)
const editForm = reactive({
  actual_start_time: '',
  actual_end_time: '',
  start_date: '',
  start_time: '',
  end_date: '',
  end_time: '',
  notes: ''
})

/**
 * 加载订单详情
 */
const loadOrderDetail = async () => {
  if (!orderId.value) return
  
  loading.value = true
  try {
    const response = await request({
      url: `/api/parking-operator/orders/${orderId.value}`,
      method: 'GET'
    })

    if (response.success) {
      orderDetail.value = response.data
      initEditForm()
    } else {
      uni.showToast({
        title: response.message || '加载失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载订单详情失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 初始化编辑表单
 */
const initEditForm = () => {
  if (!orderDetail.value) return
  
  const startDateTime = orderDetail.value.actual_start_time ? parseDateTime(orderDetail.value.actual_start_time) : null
  const endDateTime = orderDetail.value.actual_end_time ? parseDateTime(orderDetail.value.actual_end_time) : null
  
  Object.assign(editForm, {
    actual_start_time: orderDetail.value.actual_start_time || '',
    actual_end_time: orderDetail.value.actual_end_time || '',
    start_date: startDateTime ? startDateTime.date : '',
    start_time: startDateTime ? startDateTime.time : '',
    end_date: endDateTime ? endDateTime.date : '',
    end_time: endDateTime ? endDateTime.time : '',
    notes: ''
  })
}

/**
 * 时间选择器事件处理
 */
const onStartDateChange = (e) => {
  editForm.start_date = e.detail.value
  updateActualStartTime()
}

const onStartTimeChange = (e) => {
  editForm.start_time = e.detail.value
  updateActualStartTime()
}

const onEndDateChange = (e) => {
  editForm.end_date = e.detail.value
  updateActualEndTime()
}

const onEndTimeChange = (e) => {
  editForm.end_time = e.detail.value
  updateActualEndTime()
}

/**
 * 更新实际开始时间
 */
const updateActualStartTime = () => {
  if (editForm.start_date && editForm.start_time) {
    editForm.actual_start_time = `${editForm.start_date}T${editForm.start_time}:00`
  } else {
    editForm.actual_start_time = ''
  }
}

/**
 * 更新实际结束时间
 */
const updateActualEndTime = () => {
  if (editForm.end_date && editForm.end_time) {
    editForm.actual_end_time = `${editForm.end_date}T${editForm.end_time}:00`
  } else {
    editForm.actual_end_time = ''
  }
}

/**
 * 解析日期时间
 */
const parseDateTime = (dateTime) => {
  if (!dateTime) return null
  
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return {
    date: `${year}-${month}-${day}`,
    time: `${hours}:${minutes}`
  }
}

/**
 * 保存订单时间
 */
const saveOrderTime = async () => {
  // 检查是否至少选择了一个时间
  const hasStartTime = editForm.start_date && editForm.start_time
  const hasEndTime = editForm.end_date && editForm.end_time
  
  if (!hasStartTime && !hasEndTime) {
    uni.showToast({
      title: '请至少选择一个时间',
      icon: 'none'
    })
    return
  }

  // 验证时间逻辑
  if (hasStartTime && hasEndTime) {
    const startDateTime = new Date(`${editForm.start_date}T${editForm.start_time}:00`)
    const endDateTime = new Date(`${editForm.end_date}T${editForm.end_time}:00`)
    
    if (endDateTime <= startDateTime) {
      uni.showToast({
        title: '离场时间必须晚于入场时间',
        icon: 'none'
      })
      return
    }
  }

  try {
    const updateData = {}
    
    if (hasStartTime) {
      updateData.actual_start_time = editForm.actual_start_time
    }
    
    if (hasEndTime) {
      updateData.actual_end_time = editForm.actual_end_time
    }
    
    if (editForm.notes) {
      updateData.notes = editForm.notes
    }

    const response = await request({
      url: `/api/parking-operator/orders/${orderId.value}/actual-time`,
      method: 'PUT',
      data: updateData
    })

    if (response.success) {
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
      
      // 重新加载订单详情
      loadOrderDetail()
      
      // 清空备注
      editForm.notes = ''
    } else {
      uni.showToast({
        title: response.message || '更新失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('更新订单时间失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    'pending_payment': '待支付',
    'in_progress': '进行中',
    'pending_additional_payment': '待补款',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

/**
 * 获取状态样式类
 */
const getStatusClass = (status) => {
  return `status-${status}`
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 生命周期钩子
onLoad((options) => {
  if (options.id) {
    orderId.value = options.id
    loadOrderDetail()
  } else {
    uni.showToast({
      title: '订单ID不存在',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
})

// 应用权限守卫
if (parkingOperatorGuard && parkingOperatorGuard.created) {
  parkingOperatorGuard.created.call({})
}
</script>

<style scoped>
.order-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background-color: #fff;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #eee;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.detail-content {
  padding: 30rpx;
}

.detail-section {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.edit-time-section {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.detail-row {
  display: flex;
  margin-bottom: 15rpx;
  font-size: 28rpx;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: #666;
  width: 160rpx;
  flex-shrink: 0;
}

.detail-value {
  color: #333;
  flex: 1;
}

.detail-value.amount {
  color: #ff6b35;
  font-weight: bold;
}

/* 状态样式 */
.status-pending_payment {
  color: #ff9500;
  font-weight: bold;
}

.status-in_progress {
  color: #007aff;
  font-weight: bold;
}

.status-completed {
  color: #34c759;
  font-weight: bold;
}

.status-cancelled {
  color: #ff3b30;
  font-weight: bold;
}

/* 停车类型样式 */
.detail-value.parking-type.indoor {
  color: #007aff;
  font-weight: bold;
}

.detail-value.parking-type.outdoor {
  color: #ff9500;
  font-weight: bold;
}

/* 时间编辑区域 */
.time-edit-row {
  margin-bottom: 30rpx;
}

.time-edit-row:last-child {
  margin-bottom: 0;
}

.time-edit-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  font-weight: 500;
}

.datetime-picker {
  display: flex;
  gap: 20rpx;
}

.datetime-value {
  color: #333;
  font-size: 28rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  flex: 1;
  text-align: center;
  min-width: 200rpx;
  border: 2rpx solid #ddd;
}

.datetime-value:active {
  background-color: #e6f3ff;
  border-color: #007aff;
}

.time-edit-textarea {
  width: 100%;
  height: 120rpx;
  border: 2rpx solid #ddd;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  resize: none;
  background-color: #fff;
}

.time-edit-textarea:focus {
  border-color: #007aff;
}

.save-actions {
  margin-top: 30rpx;
  text-align: center;
}

.save-btn {
  width: 100%;
  height: 80rpx;
  background: #007aff;
  color: white;
  border: none;
  border-radius: 10rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.save-btn:active {
  background: #0056cc;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}
</style>